import logging
import logging.handlers
import os

from flask import request


class RequestShoppingFormatter(logging.Formatter):
    """
        自定义的日志输出格式
    """

    def format(self, record):
        record.url = request.url  # 请求地址
        record.remote_addr = request.remote_addr
        return super().format(record)


def create_logger(app):
    """
        设置日志配置
    :param app: flask中的app对象
    :return:
    """
    logging_level = app.config['LOGGING_LEVEL']
    logging_file_dir = app.config['LOGGING_FILE_DIR']
    logging_file_max_bytes = app.config['LOGGING_FILE_MAX_BYTES']
    logging_file_backup = app.config['LOGGING_FILE_BACKUP']

    request_formatter = RequestShoppingFormatter(
        '[%(asctime)s] %(remote_addr)s 请求%(url)s \t %(levelname)s 在 %(module)s %(lineno)d : %(message)s ')

    if os.path.isdir(logging_file_dir):
        pass
    else:
        os.mkdir(logging_file_dir)

    flask_file_handler = logging.handlers.RotatingFileHandler(filename=os.path.join(logging_file_dir, 'shopping.log'),
                                                              maxBytes=logging_file_max_bytes,
                                                              backupCount=logging_file_backup)

    flask_file_handler.setFormatter(request_formatter)
    flask_logger = logging.getLogger('shopping')

    flask_logger.addHandler(flask_file_handler)
    flask_logger.setLevel(logging_level)

    flask_console_handler = logging.StreamHandler()
    flask_console_handler.setFormatter(
        logging.Formatter('[%(asctime)s] %(levelname)s 在 %(module)s %(lineno)d : %(message)s'))

    if app.debug:
        flask_logger.addHandler(flask_console_handler)